//
//  AppController.m
//  QuickPost
//
//  Created by Chen Xianan on 2/3/09.
//  Copyright 2009 sk. All rights reserved.
//

#import "AppController.h"
#import "PreferenceController.h"
#import "PostWindowController.h"

NSString * const QP_ACCOUNTS_KEY = @"accounts";

// get statusItem's frame
// got it from Google
@interface NSStatusItem (Hack)
- (NSRect)hackFrame;
@end

@implementation NSStatusItem (Hack)
- (NSRect)hackFrame
{
    return [_fWindow frame];
}
@end

@implementation AppController

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
	statusItem = [[[NSStatusBar systemStatusBar]
					  statusItemWithLength:NSSquareStatusItemLength] retain];
	[statusItem setHighlightMode:YES];
	[statusItem setToolTip:@"QuickPost"];
	[statusItem setImage:[NSImage imageNamed:@"qp.png"]];
	[statusItem setAlternateImage:[NSImage imageNamed:@"qp_alt.png"]];
	[statusItem setAction:@selector(clickStatusBarItem)];

	prefCtrl = [[PreferenceController alloc] init];
	postCtrl = [[PostWindowController alloc] init];
}

- (void)clickStatusBarItem
{
	NSPanel *panel = (NSPanel *)[postCtrl window];
	if ([NSApp isActive] && [panel isVisible]) return;
	NSRect sItemFrame = [statusItem hackFrame];
	NSRect scrnFrame = [[NSScreen mainScreen] frame];
	NSRect scrnVFrame = [[NSScreen mainScreen] visibleFrame];
	NSRect panelFrame = [panel frame];
	float x;
	float y = scrnFrame.size.height - panelFrame.size.height - sItemFrame.size.height - 2;
	if (sItemFrame.origin.x + panelFrame.size.width > scrnVFrame.size.width){
		x = scrnVFrame.size.width - panelFrame.size.width;
	} else {
		x = sItemFrame.origin.x;
	}
	x -= 45;
	[panel setFrameOrigin:NSMakePoint(x, y)];
	[NSApp activateIgnoringOtherApps:YES];
	[postCtrl showWindow:statusItem];
	[prefCtrl showWindow:statusItem];
}

- (void)dealloc
{
	[statusItem release];
	[prefCtrl release];
	[postCtrl release];
	[super dealloc];
}

@end
